package com.javawork.juc.readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhangxiaolu
 * @since 2023-02-19 22:39
 */
public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                myResource.write(finalI + "", finalI + "");
            }, "写入" + String.valueOf(i)).start();

        }

        for (int i = 0; i < 10; i++) {
            int finalJ = i;
            new Thread(() -> {
                myResource.read(finalJ + "");
            }, "读取" + String.valueOf(i)).start();
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 3; i++) {
            int finalQ = i;
            new Thread(() -> {
                myResource.write(finalQ + "", finalQ + "");
            }, "新写入" + String.valueOf(i)).start();
        }
    }

}

class MyResource {
    Map<String, String> map = new HashMap<>();

    // ReentrantLock 等价于 synchronized
    Lock lock = new ReentrantLock();

    // 一体两面，读写互斥，读读共享，读未完成前，写锁不能获得
    ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void write(String key, String value) {
//        lock.lock();
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t 正在写入");
            map.put(key, value);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t 完成写入");
        } finally {
//            lock.unlock();
            rwLock.writeLock().unlock();
        }
    }

    public void read(String key) {
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t 正在读取");
            String result = map.get(key);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t 完成读取：" + "\t" + result);
        } finally {
            rwLock.readLock().unlock();
        }
    }
}